package com.heba.greenmulu.scan;

import android.os.Bundle;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.heba.Cfg;
import com.heba.adapter.QuickAdapter;
import com.heba.bean.category.OptionLevel3Object;
import com.heba.bean.product.ItemProductSearchObject;
import com.heba.config.CommonConfig;
import com.heba.event.MessageEvent;
import com.heba.greenmulu.BaseActivity;
import com.heba.greenmulu.R;
import com.heba.helper.HttpClientHelper;
import com.heba.helper.JSONHttpHelper;
import com.heba.helper.MemberShipHelper;
import com.heba.popupwindow.SortPopupWindow;
import com.heba.utils.GlideUtil;
import com.loopj.android.http.RequestParams;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

/**
 * 產品篩選
 * Created by jason on 2020/1/8.
 */
public class ItemProductSearchResultActivity extends BaseActivity {

    private View view_background;
    private View view_sort;
    private View view_filter;

    private SmartRefreshLayout refreshLayout;
    private RecyclerView rv_view;

    private QuickAdapter recycleAdapter;


    /**
     * 排序弹出框
     */
    private SortPopupWindow popupWindow;

    /**
     * 产品列表数据
     */
    private List<ItemProductSearchObject> productSearchObjectList;

    private String searchTitle;  //标题
    private int categoryID;    //分类id
    private int categoryLevel;   //分类层级
    private String keyword;    //关键词
    private String hotKeyword;   //热门关键词
    private String optionIds;    //筛选id,逗号隔开
    private int sort = 1;   //排序模式  1：最新，2：最爱，3：热门，4：品牌名称A-Z，5：产品名称A-Z
    private int intentFromSearch;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_scan_product_search_result);
        EventBus.getDefault().register(this);
        initTopbar();
        findViewById();
        initView();
        initPopupWindow();
        getProductData();
    }

    @Override
    protected void findViewById() {
        view_background = findViewById(R.id.view_background);
        view_sort = findViewById(R.id.view_sort);
        view_filter = findViewById(R.id.view_filter);
        refreshLayout = findViewById(R.id.refreshLayout);
        rv_view = findViewById(R.id.rv_view);

        /**
         * 設置文字和圖標
         */
        ((TextView) view_sort.findViewById(R.id.tv_content)).setText(R.string.scan_filter_sort);
        ((TextView) view_filter.findViewById(R.id.tv_content)).setText(R.string.scan_filter_filter);
        ((ImageView) view_sort.findViewById(R.id.iv_icon)).setImageResource(R.drawable.image_sort_selector);
        ((ImageView) view_filter.findViewById(R.id.iv_icon)).setImageResource(R.drawable.image_filter_selector);
    }

    @Override
    protected void initView() {
        Bundle bundle = getIntent().getExtras();
        if (null != bundle) {
            searchTitle = bundle.getString(CommonConfig.PRODUCT_SEARCH_TITLE, "");
            categoryID = bundle.getInt(CommonConfig.CATEGORY_ID, 0);
            categoryLevel = bundle.getInt(CommonConfig.CATEGORY_LEVEL, 0);
            keyword = bundle.getString(CommonConfig.PRODUCT_KEYWORD, "");
            hotKeyword = bundle.getString(CommonConfig.PRODUCT_HOT_KEYWORD, "");
            intentFromSearch = bundle.getInt(CommonConfig.PRODUCT_SEARCH_INTENT, 0);
        }

        productSearchObjectList = new ArrayList<>();

        txt_title.setText(searchTitle);

        /**
         * 排序按钮监听
         */
        view_sort.setOnClickListener(v -> {
            view_sort.setSelected(true);
            view_filter.setSelected(false);
            view_background.setVisibility(View.VISIBLE);
            popupWindow.showAsDropDown(view_sort, 0, 0);
        });

        /**
         * 筛选按钮监听
         */
        view_filter.setOnClickListener(v -> {
            view_sort.setSelected(false);
            view_filter.setSelected(true);
            Bundle bundle1 = new Bundle();
            bundle1.putInt(CommonConfig.CATEGORY_ID, categoryID);
            bundle1.putInt(CommonConfig.CATEGORY_LEVEL, categoryLevel);
            openActivity(ItemProductOptionCategoryActivity.class, bundle1);
        });

        /**
         * adapter
         */
        recycleAdapter = new QuickAdapter<ItemProductSearchObject>(productSearchObjectList) {
            @Override
            public int getLayoutId(int viewType) {
                return R.layout.item_scan_product;
            }

            @Override
            public void convert(VH holder, ItemProductSearchObject data, int position) {
                ImageView iv_photo = holder.getView(R.id.img_photo);
                holder.setText(R.id.txt_product, data.getBrandName());
                holder.setText(R.id.txt_content, data.getProductName());
                GlideUtil.loadImageWithDefaultPlaceHolder(ItemProductSearchResultActivity.this, data.getIcon(), iv_photo);

                /**
                 * 进去产品页面
                 */
                holder.itemView.setOnClickListener(v -> {
                    //记录搜索记录
                    if (intentFromSearch == CommonConfig.PRODUCT_SEARCH_TYPE) {
                        new MemberShipHelper(new MemberShipHelper.MembershipListener() {
                            @Override
                            public void Success() {

                            }

                            @Override
                            public void Fail(String error) {
                            }
                        }).handleRecentLog(mContext, CommonConfig.HANDLER_ADD, CommonConfig.HANDLE_TYPE_PRODUCT, 0, Integer.parseInt(data.getProductID()));
                    }

                    Bundle bundle1 = new Bundle();
                    bundle1.putString(CommonConfig.PRODUCT_ID, data.getProductID());
                    openActivity(ItemProductDetailActivity.class, bundle1);
                });
            }
        };

        /**
         * 设置layoutManager布局
         */
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        //设置布局管理器
        rv_view.setLayoutManager(layoutManager);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        //设置Adapter
        rv_view.setAdapter(recycleAdapter);

        //设置是否监听滚动到底部是触发自动刷新
        refreshLayout.setEnableAutoLoadMore(false);

        /**
         * 处理下拉刷新事件
         */
        refreshLayout.setOnRefreshListener(refreshLayout -> {
            Page = 1;
            isRefreshFromTop = true;
            getProductData();
        });

        /**
         * 处理上拉加载事件
         */
        refreshLayout.setOnLoadMoreListener(refreshLayout -> {
            Page++;
            isRefreshFromTop = false;
            getProductData();
        });
    }

    /**
     * initPopupWindow
     */
    private void initPopupWindow() {
        popupWindow = new SortPopupWindow(this, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);

        popupWindow.setOnSortClickListener(id -> {
            sort = id;
            refreshProductListData();
        });

        popupWindow.setOnDismissListener(() -> view_background.setVisibility(View.GONE));
    }

    /**
     * 更新产品列表数据
     */
    private void refreshProductListData() {
        Page = 1;
        isRefreshFromTop = true;
        getProductData();
    }

    /**
     * 获取产品列表
     */
    private void getProductData() {
        if (firstRefresh) {
            firstRefresh = false;
            progressDialog.show();
        }
        HttpClientHelper client = new HttpClientHelper();
        client.setUseLogin(true);
        RequestParams params = new RequestParams();
        params.put("Leng", Cfg.Leng);
        params.put("p", Page);
        params.put("pp", PerPage);
        params.put("Categoryid", categoryID);
        params.put("Categorylevel", categoryLevel);
        params.put("Keyword", keyword);
        params.put("HotKeyword", hotKeyword);
        params.put("Optionids", optionIds);
        params.put("Sort", sort);
        client.get(Cfg.BaseUrl + "/Product/ProductList", params,
                new JSONHttpHelper.JSONHttpResponseHandler(this) {

                    @Override
                    public void Success() {
                        // TODO Auto-generated method stub
                        super.Success();
                        progressDialog.dismiss();
                        closeRefreshView(refreshLayout);

                        /**
                         * 下拉刷新处理
                         */
                        if (isRefreshFromTop) {
                            isRefreshFromTop = false;
                            refreshLayout.setNoMoreData(false);
                            productSearchObjectList.clear();
                        }

                        try {
                            JSONArray array = new JSONObject(response.trim()).getJSONArray("Result");
                            if (array.length() > 0) {
                                List<ItemProductSearchObject> searchObjects = new Gson().fromJson(array.toString(), new TypeToken<List<ItemProductSearchObject>>() {
                                }.getType());
                                productSearchObjectList.addAll(productSearchObjectList.size(), searchObjects);
                            } else {
                                //无数据
                                refreshLayout.finishLoadMoreWithNoMoreData();
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                        //刷新数据
                        recycleAdapter.notifyDataSetChanged();
                    }

                    public void Failure() {
                        super.Failure();
                        progressDialog.dismiss();
                        closeRefreshView(refreshLayout);
                    }

                });
    }

    /**
     * 更新筛选数据
     */
    private void updateOptionData(List<OptionLevel3Object> list) {
        StringBuffer sb = new StringBuffer();
        for (OptionLevel3Object object : list) {
            sb.append(object.getOptionID());
            sb.append(",");
        }
        if (sb.length() > 0) {
            optionIds = sb.deleteCharAt(sb.length() - 1).toString();
        } else {
            optionIds = "";
        }

        /**
         * 刷新数据
         */
        refreshProductListData();
    }

    /**
     * 接收EventBus
     *
     * @param event
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(MessageEvent event) {
        /**
         * 接收选中的筛选数据
         */
        if (event.getEvent().equals(CommonConfig.OPTION_LIST)) {
            List<OptionLevel3Object> level3ObjectList = event.getOptionLevel3ObjectList();
            updateOptionData(level3ObjectList);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}
